// Carousel component
import React, { Component } from 'react';
import { Toast, Modal } from 'antd-mobile';
import './banner.less'
export default class Carousel extends Component {
    constructor(props) {
        super(props);
        this.state = { currentIndex: 0, };
        this.renderChildren = this.renderChildren.bind(this);
        this.setIndex = this.setIndex.bind(this);
    }
    renderChildren() {
        const { children, width, height } = this.props;
        const childStyle = {
            width: width,
            height: height
        };
        return React.Children.map(children, child => {
            const childClone = React.cloneElement(child, { style: childStyle });
            return (
                <div
                    style={{
                        display: 'inline-block'
                    }}
                >
                    {childClone}
                </div>

            );
        });
    }
    setIndex(index) {
        const len = this.props.children.length;
        console.log("length" + len);
        const nextIndex = (index + len) % len;
        this.setState({ currentIndex: nextIndex, });
    }


    handleTouchStart = (e) => {
        this.startX = e.touches[0].clientX;
    }
    handleTouchMove = (e) => {
        this.endX = e.touches[0].clientX;
    }
    handleTouchEnd = (e) => {
        let distance = Math.abs(this.startX - this.endX);
        let currentIndex = this.state.currentIndex;
        if (distance > 50) {
            if (this.startX > this.endX) {
                this.setIndex(currentIndex - 1)
            } else {
                this.setIndex(currentIndex + 1)
            }
        }
    }
    render() {
        const { width, height } = this.props;
        const { currentIndex } = this.state;

        const offset = -currentIndex * width;

        const frameStyle = {
            width: width,
            height: height,
            whiteSpace: 'nowrap',
            overflow: 'hidden',

        };

        const imageRowStyle = {
            marginLeft: offset,
            transition: '.2s',
            background: 'red',
        };
        return (
            <div className="carousel">
                <div className="frame" style={frameStyle}>
                    <div
                        onTouchStart={this.handleTouchStart}
                        onTouchMove={this.handleTouchMove}
                        onTouchEnd={this.handleTouchEnd}
                        //    onClick={() => this.setIndex(currentIndex + 1)}
                        style={imageRowStyle}>{this.renderChildren()}

                    </div>
                </div>
                <div className="tag">
                    <p>{this.state.currentIndex + 1}/{this.props.children.length}</p>
                </div>
            </div>
        );
    }
}